package com.milo.thread.create.callable;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;

/**
 * @author Milo Lee
 * @date 2022-03-07 11:31
 */
@Slf4j
public class CallableTest2 {
    public static final int MAX_TURN = 5;
    public static final int COMPUTE_TIMES = 100000000;

    static class ReturnAbleTask implements Callable<Long> {

        @Override
        public Long call() throws Exception {
            long start = System.currentTimeMillis();
            log.info(Thread.currentThread().getName() + "线程开始运行");
            TimeUnit.MILLISECONDS.sleep(1000);
            for (int i = 0; i < COMPUTE_TIMES; i++) {
                int j = i * 10000;
            }
            long used = System.currentTimeMillis() - start;
            log.info(Thread.currentThread().getName() + "线程执行结束");
            return used;
        }
    }

    public static void main(String[] args) {
        ReturnAbleTask returnAbleTask = new ReturnAbleTask();
        FutureTask<Long> futureTask = new FutureTask<>(returnAbleTask);
        Thread thread = new Thread(futureTask, "returnableThread");
        thread.start();
        log.info(Thread.currentThread().getName() + "让子弹飞一会");
        log.info(Thread.currentThread().getName() + "看会NBA");
        for (int i = 0; i < COMPUTE_TIMES / 2; i++) {
            int j = i * 10000;
        }
        log.info(Thread.currentThread().getName() + "获取并发任务结果");

        try {
            log.info(thread.getName() + "线程占用时间:" + futureTask.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        log.info(thread.getName() + "运行结束");
    }
}
